package sicau.carManager.config;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import sicau.carManager.Util.TokenUtil.TokenUtil;
import sicau.carManager.entity.Admin;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author ITcz
 * @Data 2021-02-17 - 22:37
 */


@Service
public class AdminArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果controller里面需要管理员的信息如校区，管理员权限等，就调用resolveArgument方法
        Class<?> clazz = parameter.getParameterType();
        if (clazz.equals(Admin.class)) {
            return true;
        }
        return false;
    }

    /**
     *  如果上面的supportsParameter方法return为true则用下面这个方法，否则不会用这个方法
     *  *  此方法给controller里注入admin的信息
    * */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader(TokenUtil.ADMIN_TOKEN);
        Admin admin = TokenUtil.getAdminByToken(token);
        return admin;
    }
}
